package cn.catsdad.base.controller;

import cn.catsdad.base.entity.BaseEntity;
import cn.catsdad.base.page.PageBean;
import cn.catsdad.base.page.PageParam;
import cn.catsdad.base.service.IBaseService;
import cn.catsdad.base.web.HttpResponse;
import cn.catsdad.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * base层controller，提供基础增删改查接口
 *
 * @author xuyl
 * @version 1.0 2024/7/14
 */
@RestController
public abstract class BaseController<T extends BaseEntity, ID extends Serializable, S extends IBaseService<T, ID>, P extends PageParam>
        extends FrameController<T> {

    protected S service;

    @GetMapping
    public HttpResponse<List<T>> pageQuery(P p) {
        PageBean<T> pageBean = getPageBean();
        service.pageQuery(pageBean, p);
        return new HttpResponse<List<T>>()
                .setData(pageBean.getQueryResult())
                .setCount(pageBean.getTotal());
    }

    /**
     * 精确查询
     *
     * @param id key
     * @return 精确查询数据
     */
    @GetMapping("/{id}")
    public HttpResponse<T> queryByKey(@PathVariable("id") ID id) {
        HttpResponse<T> result = new HttpResponse<>();
        if (id != null) {
            result.setData(service.queryByIdWithIsDeletedFalse(id));
        }
        return result;
    }

    /**
     * 单保存
     *
     * @param t 保存的实体
     * @return 保存的实体
     */
    @PostMapping
    public HttpResponse<T> save(@RequestBody T t) {
        HttpResponse<T> result = new HttpResponse<>();
        if (t != null) {
            service.save(t);
            result.setData(t);
        }
        return result;
    }


    /**
     * 更新
     *
     * @param t 保存的对象
     * @return 更新后的对象
     */
    @PutMapping
    public HttpResponse<T> update(@RequestBody T t) {
        HttpResponse<T> result = new HttpResponse<>();
        if (t != null) {
            service.save(t);
            result.setData(t);
        }
        return result;
    }

    /**
     * 批量删除
     *
     * @param ids 需要删除的数据id
     * @return 删除数据数量
     */
    @DeleteMapping
    public HttpResponse<Integer> delete(@RequestBody Collection<ID> ids) {
        HttpResponse<Integer> result = new HttpResponse<>();
        if (StringUtil.isNotEmpty(ids)) {
            service.logicDeleteByIds(ids);
            result.setData(ids.size());
        }
        return result;
    }

    @Autowired
    public void setService(S service) {
        this.service = service;
    }
}
